package com.atguigu.service.impl;

import com.atguigu.common.CustomException;
import com.atguigu.dto.DishDto;
import com.atguigu.dto.SetmealDto;
import com.atguigu.entity.Dish;
import com.atguigu.entity.Setmeal;
import com.atguigu.entity.SetmealDish;
import com.atguigu.mapper.SetmealMapper;
import com.atguigu.service.SetmealService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {
    @Resource
    private SetmealDishServiceImpl setmealDishService;

    /**
     * 新增套餐，同时需要保存套餐和菜品的关联关系
     *
     * @param setmealDto
     */
    public void addSetmealWithDish(SetmealDto setmealDto) {
        //保存套餐信息到setmeal表中
        this.save(setmealDto);
        //将菜品信息保存到Setmeal_dish表中
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        for (SetmealDish setmealDish : setmealDishes) {
            setmealDish.setSetmealId(setmealDto.getId());
        }
        //保存套餐和菜品的关联信息，操作setmeal_dish,执行insert操作
        setmealDishService.saveBatch(setmealDishes);
    }

    /**
     * 删除套餐及套餐-菜品关系
     * @param ids
     */
    @Override
    public void removeSetmealWithDish(List<Long> ids) {
        //delete from setmeal where id in ids
        //查询套餐状态，查看是否可删除
        LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper = new LambdaQueryWrapper<>();
        setmealLambdaQueryWrapper.in(Setmeal::getId,ids);
        setmealLambdaQueryWrapper.eq(Setmeal::getStatus,1);
        long count = this.count(setmealLambdaQueryWrapper);
        //如果count>0,说明所要删除的记录中有未停售的套餐，不能删除
        if(count>0){
            throw new CustomException("所要删除的记录中有未停售的套餐，不能删除");
        }
        //如果可以删除，先删除套餐表中的数据---setmeal
        this.removeByIds(ids);
        //删除相关的菜品信息
        //delete from setmeal_dish where setmeal_id in ids
        LambdaQueryWrapper<SetmealDish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishLambdaQueryWrapper.in(SetmealDish::getSetmealId,ids);
        setmealDishService.remove(dishLambdaQueryWrapper);
    }

}
